package com.gyz.cfmall.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gong_yz
 * @Description
 * @Date 2023/4/14
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String SSOServerUrl;

    /**
     * 无需认证即可访问
     *
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    @GetMapping("/boss")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            //去认证中心查询用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8082/userInfo?token=" + token, String.class);
            String body = entity.getBody();
            model.addAttribute("loginUser", body);
        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:" + SSOServerUrl + "?redirect_url=http://cliect1.com:8083/boss";
        } else {
            List<Object> emps = new ArrayList<>();
            emps.add("zhangsan");
            emps.add("lisi");
            model.addAttribute("emps", emps);
        }

        return "employees";
    }
}
